package com.elock.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.elock.base.core.ExcelView;
import com.elock.base.core.Filter;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.controller.BaseController;
import com.elock.base.core.controller.ResultMsg;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.JsonUtils;
import com.elock.base.core.util.WebUtils;
import com.elock.entity.SystemDict;
import com.elock.entity.SystemParameter;
import com.elock.entity.Terminal;
import com.elock.entity.TerminalSaleOrg;
import com.elock.service.CarService;
import com.elock.service.SaleOrgBaseService;
import com.elock.service.SystemDictBaseService;
import com.elock.service.SystemParameterBaseService;
import com.elock.service.TerminalSaleOrgService;
import com.elock.service.TerminalService;
import com.elock.util.SystemConfig;

/**
 * Controller - 终端设备
 * @author 仁德
 */
@Controller("terminalController")
@RequestMapping("/terminal")
public class TerminalController extends BaseController {

	@Resource(name = "terminalServiceImpl")
	private TerminalService terminalService;
	@Resource(name = "terminalSaleOrgServiceImpl")
	private TerminalSaleOrgService terminalSaleOrgService;
	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;
	@Resource(name = "systemDictBaseServiceImpl")
	private SystemDictBaseService systemDictBaseService;
	@Resource(name = "systemParameterBaseServiceImpl")
	private SystemParameterBaseService systemParameterService;
	@Resource(name = "carServiceImpl")
	private CarService carService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list_tb", method = RequestMethod.GET)
	public String list_tb(ModelMap model) {

		return "/terminal/list_tb";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Pageable pageable, ModelMap model) {

		return "/terminal/list";
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/list_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg list_data(String terminalNum, String terminalName,
			String sim, Long saleOrgId, Pageable pageable, ModelMap model) {

//		List<Filter> filters = new ArrayList<Filter>();
//		if (!ConvertUtil.isEmpty(terminalNum)) {
//			filters.add(Filter.like("terminalNum", "%" + terminalNum + "%"));
//		}
//		if (!ConvertUtil.isEmpty(terminalName)) {
//			filters.add(Filter.like("terminalName", "%" + terminalName + "%"));
//		}
//		if (!ConvertUtil.isEmpty(sim)) {
//			filters.add(Filter.like("sim", "%" + sim + "%"));
//		}
//		Page<Terminal> page = terminalService.findPage(filters, null, pageable);
		Page<Map<String, Object>> page = terminalService.findPage(terminalNum,
				terminalName,
				saleOrgId,
				sim,
				pageable);
		String jsonPage = JsonUtils.toJson(page);

		return success(jsonPage);
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap model) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("code", "TerminalType"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> terminalTypes = systemDictBaseService.findList(null,
				filters,
				null);
		model.addAttribute("terminalTypes", terminalTypes);

		filters.clear();
		filters.add(Filter.eq("code", "TerminalModel"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> terminalModels = systemDictBaseService.findList(null,
				filters,
				null);
		model.addAttribute("terminalModels", terminalModels);
		model.addAttribute("saleOrg", saleOrgBaseService.getCurrentSaleOrg());

		SystemParameter isUseTask = systemParameterService.getAdminParam("isUseTask");
		model.addAttribute("isUseTask", isUseTask);

		return "/terminal/add";
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public @ResponseBody ResultMsg save(Terminal terminal, Long saleOrgId, Long[] carId,
			Long typeId, Long modelId) {

		if (ConvertUtil.isEmpty(terminal.getTerminalNum())) {
			return error("请填写终端设备编号");
		}
		if (terminal.getTerminalNum().length() != 8) {
			return error("终端设备编号必须是8个字符，请重新维护");
		}
//		if (terminal.getSim().length() != 11) {
//			return error("终端SIM卡号必须是11位数字，请重新维护");
//		}
//		if (terminalService.exists(Filter.eq("terminalNum", terminal.getTerminalNum()))) {
//			return error("该终端设备编号已存在");
//		}
		Terminal t = terminalService.findByCarNumber(terminal.getTerminalNum());
		if (t != null) {
			return error("该终端设备编号在系统中已存在");
		}
		if (typeId != null) {
			terminal.setType(systemDictBaseService.find(typeId));
		}
		if (modelId != null) {
			terminal.setModel(systemDictBaseService.find(modelId));
		}

		terminalService.save(terminal, saleOrgId, carId);

		return success().addObjX(terminal.getId());
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, ModelMap model) {

		Terminal terminal = terminalService.find(id);
		model.addAttribute("terminal", terminal);

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("terminalId", terminal.getId()));
		TerminalSaleOrg terminalSaleOrg = terminalSaleOrgService.find(filters);
		if (terminalSaleOrg != null) {
			model.addAttribute("saleOrg",
					saleOrgBaseService.find(terminalSaleOrg.getSaleOrgId()));
		}
		else {
			model.addAttribute("saleOrg", saleOrgBaseService.getCurrentSaleOrg());
		}

		List<Map<String, Object>> electronicFence = terminalService
				.findTerminalElectronicFenceByTerminalId(id);
		model.addAttribute("electronicFence", JsonUtils.toJson(electronicFence));

		filters.clear();
		filters.add(Filter.eq("code", "TerminalType"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> terminalTypes = systemDictBaseService.findList(null,
				filters,
				null);
		model.addAttribute("terminalTypes", terminalTypes);

		filters.clear();
		filters.add(Filter.eq("code", "TerminalModel"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> terminalModels = systemDictBaseService.findList(null,
				filters,
				null);
		model.addAttribute("terminalModels", terminalModels);

		SystemParameter isUseTask = systemParameterService.getAdminParam("isUseTask");
		model.addAttribute("isUseTask", isUseTask);

		List<Map<String, Object>> terminalCars = carService.findByTerminalId(id);
		model.addAttribute("terminalCars", JsonUtils.toJson(terminalCars));

		return "/terminal/edit";
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody ResultMsg update(Terminal terminal, Long saleOrgId, Long[] carId,
			Long typeId, Long modelId) {

		if (ConvertUtil.isEmpty(terminal.getTerminalNum())) {
			return error("请填写终端设备编号");
		}
		if (terminal.getTerminalNum().length() != 8) {
			return error("终端设备编号必须是8个字符，请重新维护");
		}
//		if (terminal.getSim().length() != 11) {
//			return error("终端SIM卡号必须是11位数字，请重新维护");
//		}
//		if (terminalService.exists(Filter.eq("terminalNum", terminal.getTerminalNum()),
//				Filter.ne("id", terminal.getId()))) {
//			return error("该终端设备编号已存在");
//		}
		Terminal t = terminalService.findByCarNumber(terminal.getTerminalNum());
		if (t != null && !t.getId().equals(terminal.getId())) {
			return error("该终端设备编号在系统中已存在");
		}
		if (typeId != null) {
			terminal.setType(systemDictBaseService.find(typeId));
		}
		if (modelId != null) {
			terminal.setModel(systemDictBaseService.find(modelId));
		}
		terminalService.update(terminal, saleOrgId, carId);

		return success();
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody ResultMsg delete(Long[] ids) {

		terminalService.delete(ids);
		return success();

	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/select_list", method = RequestMethod.GET)
	public String select_list(Pageable pageable, Integer multi, Long saleOrgId,
			ModelMap model) {

		model.addAttribute("multi", multi);
		model.addAttribute("saleOrgId", saleOrgId);
		return "/terminal/select_list";
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/select_list_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg select_list_data(String terminalNum,
			String terminalName, String sim, Long saleOrgId, Pageable pageable,
			ModelMap model) {

		Page<Map<String, Object>> page = terminalService.findPage(terminalNum,
				terminalName,
				saleOrgId,
				sim,
				pageable);
		String jsonPage = JsonUtils.toJson(page);

		return success(jsonPage);
	}

	/**
	 * Excel导入
	 */
	@RequestMapping(value = "/import_excel", method = RequestMethod.POST)
	public @ResponseBody ResultMsg importFromExcel(MultipartFile file) throws Exception {

		terminalService.terminalImport(file);
		return ResultMsg.success();
	}

	@RequestMapping(value = "/to_condition_export", method = RequestMethod.POST)
	public @ResponseBody List<Map<String, Object>> toConditionExport(String terminalNum,
			String terminalName, String sim, Long saleOrgId, Pageable pageable,
			ModelMap model) {

		Integer size = terminalService.countTerminalList(terminalNum,
				terminalName,
				saleOrgId,
				sim,
				pageable,
				null,
				null);
		List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
		Map<String, Integer> segments = getSegment();
		int stage = segments.get("segment");
		int page_size = segments.get("size");
		for (int i = 0; i < stage; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			int total = i * page_size;
			if (size == 0) {
				map.put("data", "0-0");
			}
			else if ((size - total) <= page_size) {
				map.put("data", (total + 1) + "-" + size);
			}
			else {
				map.put("data", (total + 1) + "-" + (i + 1) * page_size);
			}
			lists.add(map);
			if ((size - total) <= page_size) {
				break;
			}
		}
		return lists;
	}

	/**
	 * 条件导出
	 * @return
	 */
	@RequestMapping(value = "/condition_export", method = RequestMethod.GET)
	public ModelAndView conditionExport(String terminalNum, String terminalName,
			String sim, Long saleOrgId, Pageable pageable, ModelMap model, Integer page) {

		Map<String, Integer> segments = getSegment();
		int size = segments.get("size");
		List<Map<String, Object>> data = terminalService.findTerminalList(terminalNum,
				terminalName,
				saleOrgId,
				sim,
				pageable,
				page,
				size);
		return this.getModelAndView(data, model);

	}

	public ModelAndView getModelAndView(List<Map<String, Object>> data, ModelMap model) {
		for (Map<String, Object> str : data) {
			Boolean is_jzdw = (Boolean) str.get("is_jzdw");
			if (is_jzdw) {
				str.put("is_jzdw", "是");
			}
			else {
				str.put("is_jzdw", "否");
			}
			Boolean is_manual_unlock = (Boolean) str.get("is_manual_unlock");
			if (is_manual_unlock) {
				str.put("is_manual_unlock", "是");
			}
			else {
				str.put("is_manual_unlock", "否");
			}
			Boolean is_manual_remove_warn = (Boolean) str.get("is_manual_remove_warn");
			if (is_manual_remove_warn) {
				str.put("is_manual_remove_warn", "是");
			}
			else {
				str.put("is_manual_remove_warn", "否");
			}
		}

		//设置导出表格名
		String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xls";
		//设置标题
		String[] header = { "终端设备编号",
				"终端设备名称",
				"终端SIM卡号",
				"终端设备类型",
				"终端设备型号",
				"机构名称",
				"是否开启基站定位",
				"是否手动开锁",
				"是否手动解除报警",
				"备注" };
		//设置单元格取值
		String[] properties = { "terminal_num",
				"terminal_name",
				"sim",
				"type_value",
				"model_value",
				"sale_org_name",
				"is_jzdw",
				"is_manual_unlock",
				"is_manual_remove_warn",
				"remark" };

		return new ModelAndView(
				new ExcelView(filename, null, properties, header, null, null, data, null),
				model);
	}

	private Map<String, Integer> getSegment() {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		try {
			String value = SystemConfig.getConfig("SegmentExportConfig",
					WebUtils.getCurrentCompanyInfoId());
			String[] values = value.split(",");
			map.put("segment", Integer.parseInt(values[0]));
			map.put("size", Integer.parseInt(values[1]));
		}
		catch (Exception e) {
			map.put("segment", 10);
			map.put("size", 1000);
		}
		return map;
	}
}
